var path = require("path");
var dao = require(path.join(process.cwd(), "dao/DAO"));
var formatData = require("./formatData.js");
var upload_config = require('config').get("upload_config");

function doCreateCartSku(sku) {
    return new Promise(function (resolve, reject) {
        dao.create("CartSkuModel", sku, function (err, newSku) {
            if (err) return reject({
                msg: "添加购物车：商品规格保存到数据库失败！",
                code: 500,
                stack: err
            });
            resolve(newSku);
        })
    });
}

function doCreateCart(params, cb) {
    dao.create("CartModel", params, function (err, cart) {
        if (err) return cb({
            msg: "添加购物车：添加失败！",
            code: err.name == "SequelizeValidationError" ? 400 : 500,
            stack: err
        });
        let createFns = [];
        params.good_sku.forEach(function (sku) {
            createFns.push(doCreateCartSku({
                ...sku,
                cart_id: cart.id
            }));
        })
        if (createFns.length == 0) return cb(null, {
            msg: "添加购物车：添加成功！",
            code: 201,
            data: formatData(cart)
        });
        Promise.all(createFns).then(function () {
            cb(null, {
                msg: "添加购物车：添加成功！",
                code: 201,
                data: formatData(cart)
            });
        }).catch(cb);
    });
}

function doUpdateCart(id, good_count, cb) {
    if (!id || isNaN(parseInt(id))) return cb({
        msg: "更新购物车：ID不合法！",
        code: 400,
        stack: null
    });
    if (!good_count || isNaN(parseInt(good_count))) return cb({
        msg: "更新购物车：商品数量不合法！",
        code: 400,
        stack: null
    });
    dao.update("CartModel", id, { good_count }, function (err, cart) {
        if (err) return cb({
            msg: "更新购物车：更新失败！",
            code: err.name == "SequelizeValidationError" ? 400 : 500,
            stack: err
        });
        cb(null, {
            msg: "更新购物车：更新成功！",
            code: 200,
            data: formatData(cart)
        });
    });
}
/**
 *  添加购物车
 * 
 *  @param {[type]}   params 购物车数据 
 *  @param {Function} cb  回调函数
 */
module.exports.createCart = function (params, cb) {
    var conditions = {
        where: {
            user_id: params.user_id,
            good_id: params.good_id
        }
    };
    conditions["include"] = [{
        association: global.database.association["cart_sku"],
        attributes: ["sku_name", "sku_value"]
    }];
    dao.list("CartModel", conditions, function (err, cart) {
        if (err) return cb({
            msg: "添加购物车：添加失败！",
            code: err.name == "SequelizeValidationError" ? 400 : 500,
            stack: err
        });
        // 如果购物车中不存在对应的商品
        // 则添加到购物车中
        if (!cart.length) {
            return doCreateCart(params, cb);
        }
        // 对比提交的sku和数据库中的sku
        // 得到需要更新的购物车商品
        let cart_good;
        for (let i = 0; i < cart.length; i++) {
            let diffRes = [], isSameSku;
            if (cart[i].good_sku.length == params.good_sku.length) {
                for (let j = 0; j < cart[i].good_sku.length; j++) {
                    let sku = cart[i].good_sku[j];
                    let index = params.good_sku.findIndex(it => {
                        return it.sku_name == sku.sku_name && it.sku_value == sku.sku_value;
                    });
                    diffRes.push(index);
                }
                isSameSku = diffRes.every(it => it > -1);
                if (isSameSku) {
                    cart_good = cart[i];
                    break;
                }
            }
        }
        // 如果购物车中存在对应的商品，并且规格相同
        // 则更新数量
        if (cart_good) {
            doUpdateCart(cart_good.id, parseInt(cart_good.good_count) + parseInt(params.good_count), cb)
        }
        // 如果购物车中存在对应的商品，但是规格不同
        // 则创建新购物车数据
        if (!cart_good) {
            doCreateCart(params, cb);
        }
    })
}

/**
 *  删除购物车
 * 
 *  @param  {[type]}   id     购物车ID
 *  @param  {Function} cb     回调函数
 */
module.exports.deleteCart = function (id, cb) {
    if (!id) return cb({
        msg: "删除购物车：ID不能为空！",
        code: 400,
        stack: null
    });
    if (!Array.isArray(id)) id = [id];
    if (id.every(item => isNaN(parseInt(item)))) return cb({
        msg: "删除购物车：ID必须是数字！",
        code: 400,
        stack: null
    });
    dao.destroyMany("CartModel", id, function (err) {
        if (err) return cb({
            msg: "删除购物车：删除失败！",
            code: 500,
            stack: err
        });
        cb(null, {
            msg: "删除购物车：删除成功！",
            code: 200,
            data: null
        });
    });
}

/**
 *  更新购物车
 * 
 *  @param  {[type]}   id         购物车ID
 *  @param  {[type]}   good_count 新数据
 *  @param  {Function} cb         回调函数
 */
module.exports.updateCart = doUpdateCart;


/**
 *  根据条件获取购物车分页数据
 *  @param  {[type]}   conditions 查询条件
 *  conditions{
        "where" : 条件查询,
        "order" : 排序
        "pagenum" : 页数,
        "pagesize" : 每页长度
    }
 *  @param  {Function} cb         回调函数
 */
module.exports.getPageCarts = function (conditions, cb) {
    if (!conditions.pagenum || conditions.pagenum <= 0) return cb({
        msg: "获取购物车列表：pagenum 参数不合法！",
        code: 400,
        stack: null
    });
    if (!conditions.pagesize || conditions.pagesize <= 0) return cb({
        msg: "获取购物车列表：pagesize 参数不合法！",
        code: 400,
        stack: null
    });
    dao.countByConditions("CartModel", conditions, function (err, count) {
        if (err) return cb({
            msg: "获取购物车列表：获取总数失败！",
            code: 500,
            stack: err
        });
        pagenum = parseInt(conditions["pagenum"]);
        pagesize = parseInt(conditions["pagesize"]);
        pageCount = Math.ceil(count / pagesize);
        offset = (pagenum - 1) * pagesize;
        if (offset >= count) {
            offset = count;
        }
        limit = pagesize;
        conditions["offset"] = offset;
        conditions["limit"] = limit;
        conditions["order"] = conditions["order"] || "-id";
        conditions["attributes"] = {
            include: [
                [
                    global.database.sequelize.literal(`(
                        SELECT group_concat(good_pic.mid)
                        FROM good_pic
                        WHERE good_pic.good_id = CartModel.good_id
                    )`),
                    'good_pic'
                ],
            ]
        }
        conditions["include"] = [{
            association: global.database.association["cart_good"],
            attributes: ["name", "price", "is_promote", "promote_price"]
        }, {
            association: global.database.association["cart_sku"],
            attributes: ["sku_name", "sku_value"]
        }];
        dao.list("CartModel", conditions, function (err, cart) {
            if (err) return cb({
                msg: "获取购物车列表：获取分页数据失败！",
                code: 500,
                stack: err
            });
            var resultDta = {};
            for (idx in cart) {
                var pics = cart[idx].dataValues.good_pic;
                pics = pics ? pics.split(",") : [];
                pics = pics.map(function (pic) {
                    return pic.indexOf("http") == 0 ? pic : upload_config.get("baseURL") + pic;
                });
                cart[idx].good_pic = pics;
            }
            resultDta["total"] = count;
            resultDta["pagenum"] = pagenum;
            resultDta["cart"] = cart.map(formatData);
            cb(null, {
                msg: "获取购物车列表：获取分页数据成功！",
                code: 200,
                data: resultDta
            });
        });
    });
}


/**
 *  根据条件获取购物车列表数据
 *  @param  {[type]}   conditions 查询条件
 *  conditions{
        "where" : 条件查询,
    }
 *  @param  {Function} cb         回调函数
 */
module.exports.getSearchCarts = function (conditions, cb) {
    conditions["order"] = conditions["order"] || "-id";
    conditions["attributes"] = {
        include: [
            [
                global.database.sequelize.literal(`(
                            SELECT group_concat(good_pic.mid)
                            FROM good_pic
                            WHERE good_pic.good_id = CartModel.good_id
                        )`),
                'good_pic'
            ],
        ]
    }
    conditions["include"] = [{
        association: global.database.association["cart_good"],
        attributes: ["id", "name", "price", "is_promote", "promote_price"]
    }, {
        association: global.database.association["cart_sku"],
        attributes: ["sku_name", "sku_value"]
    }];
    dao.list("CartModel", conditions, function (err, cart) {
        if (err) return cb({
            msg: "获取购物车数据失败！",
            code: 500,
            stack: err
        });
        for (idx in cart) {
            var pics = cart[idx].dataValues.good_pic;
            pics = pics ? pics.split(",") : [];
            pics = pics.map(function (pic) {
                return pic.indexOf("http") == 0 ? pic : upload_config.get("baseURL") + pic;
            });
            cart[idx].good_pic = pics;
        }
        cb(null, {
            msg: "获取购物车数据成功！",
            code: 200,
            data: cart.map(formatData)
        });
    });
}